package com.ktr.utils;

import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.fazecast.jSerialComm.SerialPort;

/**
 * @Description:
 * @ClassName:jSerialComm
 * @Author:sys
 * @Date:2019-05-20 10:40
 **/
public class SerialComm {
    public SerialComm(String portDescriptor) {
        this.portDescriptor = portDescriptor;
    }

    public SerialComm(String portDescriptor, Integer baudRate) {
        this.portDescriptor = portDescriptor;
        this.baudRate = baudRate;
    }

    private String portDescriptor;
    private Integer baudRate;

    private SerialPort comPort;

    public boolean isOpen() {
        return comPort.isOpen();
    }

    /**
     * 打开串口
     *
     * @return 打开的状态
     */
    public boolean openPort() {
        return openPort(portDescriptor, baudRate);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor) {
        return openPort(portDescriptor, null);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @param baudRate       波特率
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor, Integer baudRate) {
        comPort = SerialPort.getCommPort(portDescriptor);
        if (baudRate != null) {
            comPort.setBaudRate(baudRate);
        }
        if (!comPort.isOpen()) {
            return comPort.openPort();
        } else {
            return true;
        }
    }


    /**
     * 关闭串口
     *
     * @return
     */
    public boolean closePort() {
        if (comPort != null && comPort.isOpen()) {
            return comPort.closePort();
        }
        return true;
    }

    /**
     * 向com口发送数据并且读取数据
     */
    public byte[] writeAndRead(String instruct) {
        byte[] reslutData = null;
        try {
            if (!comPort.isOpen()) throw new SysException(SysExceptionCode.CODE_40018);

            int numWrite = comPort.writeBytes(KtrUtils.getCRC(instruct), KtrUtils.getCRC(instruct).length);
            if (numWrite > 0) {
                int i = 0;
                while (comPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
                byte[] readBuffer = new byte[comPort.bytesAvailable()];
                int numRead = comPort.readBytes(readBuffer, readBuffer.length);
                if (numRead > 0) {
                    reslutData = readBuffer;
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new SysException(e.getMessage());
        }
        return reslutData;
    }

}